# File used to import data from JIRA (bug tacker)

import sys
from jira import jira_fetcher
from issue import Issue
import couchdbkit
import threading
import time
import logging

def downloadAsRawDict (projectName, jiraAddress):
    # download jira's data as a row dictionary using Alberto Bacchelli's library 
    logging.basicConfig()
    logging.getLogger().setLevel(logging.INFO)
    issuesList = jira_fetcher.fetch_reports(system_name=projectName, wsdl=jiraAddress)
    return issuesList
    
def convertRawDicToIssueListAndSave (couchdb, database, rawDict, start=0, stop=-1):
    # convert a raw dictionary of issue into a nice list of issue
    # start and stop are optional ad used to tell where start and stop the conversion in the list of keys
    if stop==-1:
        stop = len(rawDict.keys())
    issueList = []
    keylist = sorted(rawDict.keys())
    # convert
    for bug in keylist[start:stop]:
        b = rawDict[bug]
        issue = Issue()
        issue.createIssue(b["created"], b["key"], b["reporter"], b["summary"], b["status"] , b["type"], b["priority"], b["resolution"])
        if "updated" in b.keys():
            issue.addDateUpdated(b["updated"])
        if "assignee" in b.keys():
            issue.addAssignee(b["assignee"])
        issueList.append(issue)
    # save in database
    server = couchdbkit.Server(couchdb)
    db = server.get_or_create_db(database)
    stored = 0
    for i in issueList:
        ex = i.commitToDatabase(server, db)
        if ex:
            stored += 1
    sys.stdout.write('.')
    sys.stdout.flush()
    return len(issueList), stored

class MainJIRAThread(threading.Thread):
    # thread to import in couchdb issues from jira
    
    def __init__(self, projectJiraAddress, project, couchdb, database):
        threading.Thread.__init__(self)
        self.projectJiraAddress = projectJiraAddress # the address of jira
        self.couchdb = couchdb # address of couchdb
        self.database = database # database name
        self.project = project # project name in jira
    
    def run(self):
        print "Start JIRA importer"
        start_time = time.clock()
        raw = downloadAsRawDict(self.project, self.projectJiraAddress)
        length = len(raw)
        step = 100
        iter = 0
        bugDownloaded = 0
        bugImported = 0
        print "Save into database"
        # import bugs in couchdb 100 bugs at time
        while(iter<length):
            if(iter+step<=length):
                d, i = convertRawDicToIssueListAndSave(self.couchdb, self.database, raw, iter, iter+step)
                bugDownloaded += d
                bugImported += i
            else:
                d, i = convertRawDicToIssueListAndSave(self.couchdb, self.database, raw, iter, length)
                bugDownloaded += d
                bugImported += i
            sys.stdout.write('.')
            sys.stdout.flush()
            iter += step
        end_time = time.clock()
        t = end_time-start_time
        print "\n Number issues: "+str(bugDownloaded)+"\n issues imported: "+str(bugImported)+" \n time:"+str(t)
    
#dc = downloadAsRawDict("trb", "https://issues.apache.org/jira/rpc/soap/jirasoapservice-v2?wsdl")
#convertRawDicToIssueList(dc)